import java.net.URLConnection;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.List;

public class Client {

	static int numTimes;

    public static void main(String[] args) throws IOException{
		if(args.length > 0)
			try {
				numTimes = Integer.parseInt(args[0]);
			}catch(NumberFormatException e){
				numTimes = 100;
			}
		else
			numTimes = 100;
		int attempts = 0;
		for(int i = 0; i < numTimes; ++i){
			int counter = 0;
			try{
				System.out.println("Game #"+(i+1));
				List<String> cookies = getCookies("http://localhost:8080"); //get the cookies we gonna use
				String data = "";
				int lowest = 0;
				int highest = 101;
				while(!data.contains("congrats")) { //run until we finish the game
					int guess = (highest-lowest)/2 + lowest; //binary-search
					data = getSite("http://localhost:8080/?guess="+guess, cookies); //get the content of the site
					if(data.contains("lower")){
						highest = guess;
					}else if(data.contains("higher")){
						lowest = guess;
					}
					++counter;
				}
				attempts += counter;
			}catch(Exception e){
				System.out.println("we got a "+e);
				--i;
			}
		}
		System.out.println("average num guesses: "+(float)attempts/(float)numTimes);
	}
	/**
	Connects to a site from a url and return a list of cookies
	*/
	public static List<String> getCookies(String url) throws IOException{
		URLConnection connection = new URL(url).openConnection();
		connection.addRequestProperty("Cookie", "");
		connection.setRequestProperty("Accept-Charset", "UTF-8");
		List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

		return cookies;
	}
	/**
	Connects to a site from a url and a list of cookies and returns the content of the site
	*/
	public static String getSite(String url, List<String> cookies) throws IOException{
		URLConnection connection = new URL(url).openConnection();
		//foreach cookie get the important part and add it to header
		for(String cookie : cookies) {
			connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
		}
		connection.setRequestProperty("Accept-Charset", "UTF-8"); //we use utf-8
		
		InputStream response = connection.getInputStream();	//the response		
		//let's see what we got for charset
		String contentType = connection.getHeaderField("Content-Type");
		String charset = null;
		for (String param : contentType.replace(" ", "").split(";")) {
			if (param.startsWith("charset=")) {
				charset = param.split("=", 2)[1];
				break;
			}
		}
		String data = "";
		//let's get all the content of the site
		if (charset != null) {
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(response, charset));
				for (String line; (line = reader.readLine()) != null;) {
					data += line;
				}
			} finally {
				if (reader != null) 
					try { 
						reader.close(); 
					}catch(IOException e) {}
			}
		} else {}	
		return data;
	}
}